package com.study.commomThirdPartyTechnologies.service;

import com.alibaba.fastjson.JSONObject;
import com.study.commomThirdPartyTechnologies.common.config.BaiduApiConfig;
import com.study.commomThirdPartyTechnologies.common.util.OkHttpClientUtil;
import com.study.commomThirdPartyTechnologies.model.bo.IdentifyAddressBO;
import com.study.commomThirdPartyTechnologies.model.vo.TokenVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @author wei.zhao
 * @description: 百度地址识别服务
 * @date 2022年08月04日 15:44
 */
@Service
public class IdentifyAddressService {

    @Autowired
    BaiduApiConfig baiduApiConfig;

    @Autowired
    OkHttpClientUtil okHttpClientUtil;

    /**
     * 获取API访问accessToken，该token有一定的有效期，需要自行管理，当失效时需重新获取。
     */
    public String getAccessToken() {
        // 获取token地址
        String tokenUrl = String.format(baiduApiConfig.getTokenUrl(), baiduApiConfig.getClientId(), baiduApiConfig.getClientSecret());
        TokenVo tokenVo = okHttpClientUtil.getForm(tokenUrl, null, TokenVo.class);
        return tokenVo.getAccess_token();
    }

    /**
     * 地址识别
     */
    public String identifyAddress(String addresss) {
        String accessToken = getAccessToken();
        IdentifyAddressBO identifyAddressBO = IdentifyAddressBO.builder().text(addresss).build();
        return okHttpClientUtil.postJson(String.format(baiduApiConfig.getIdentifyAddressUrl(), accessToken), JSONObject.toJSONString(identifyAddressBO));
    }

}
